<template>
  <!-- 基础布局 -->
  <el-container class="layout-container">
    <el-header class="layout-header">
      <span style="color: #fff; float: left;">{{ userName }} 您好</span>
      <audio v-show="0" id="bell" controls>
        <source :src="'11750.wav' | staticPath" type="audio/ogg" />
        <source :src="'11750.mp3' | staticPath" type="audio/mpeg" />您的浏览器不支持 audio 元素。
      </audio>
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        size="small"
        style="display: inline; margin-right: 20px;"
      >
        <el-tooltip
          class="item"
          effect="light"
          content="设置声音或弹窗播放频率(监测到异常后播放)"
          placement="bottom-end"
        >
          <el-select v-model="formInline.frequency" placeholder="选择报警时间间隔" size="small">
            <el-option label="<选择报警时间间隔(10秒)>" value="10"></el-option>
            <el-option label="5秒" value="5"></el-option>
            <el-option label="1秒" value="1"></el-option>
          </el-select>
        </el-tooltip>
        <el-form-item id="switchVoice" label="开启声音" size="small">
          <el-tooltip class="item" effect="light" content="设置是否播放声音" placement="bottom-end">
            <el-switch v-model="formInline.enableVoice"></el-switch>
          </el-tooltip>
        </el-form-item>
        <el-form-item id="switchMock" label="模拟实时接收异常预警" size="small">
          <el-tooltip
            class="item"
            effect="light"
            content="开启后，前端每0.5~3秒生成一条预警数据，模拟后端实时推送异常预警数据到前端"
            placement="bottom-end"
          >
            <el-switch v-model="formInline.enableMock"></el-switch>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <Navbar :connect="calcEnableMock" />
    </el-header>
    <el-main class="layout-main">
      <Nuxt />
    </el-main>
  </el-container>
</template>

<script>
import { mapMutations, mapGetters, mapActions } from 'vuex'
import Navbar from '@/layouts/components/Navbar'
import { generateAlarmData } from '@/utils/alarm'

export default {
  components: {
    Navbar
  },
  data() {
    return {
      formInline: {
        frequency: '10',
        enableVoice: false,
        enableMock: false
      },
      userName: '',
      mockWaitTime: 0
    }
  },
  computed: {
    ...mapGetters(['newAlarms', 'alarmData', 'enableVoice', 'enableMock']),
    /**
     * 异常预警轮询频率
     */
    calcFrequency() {
      return parseInt(this.formInline.frequency, 10) * 1000
    },
    /**
     * 声音播放开关
     */
    calcEnableVoice() {
      return this.formInline.enableVoice
    },
    /**
     * 数据模拟开关
     */
    calcEnableMock() {
      return this.formInline.enableMock
    },
    /**
     * 新产生的异常警告数据
     */
    calcNewAlarms() {
      return this.newAlarms
    }
  },
  watch: {
    enableVoice(newVal, oldVal) {
      this.formInline.enableVoice = newVal
    },
    enableMock(newVal, oldVal) {
      this.formInline.enableMock = newVal
    },
    calcFrequency(newVal, oldVal) {
      clearInterval(this.alarmTrigger)
      this.alarmTrigger = this.initAlarmTrigger()
    }
  },
  mounted() {
    // 获取初始化数据并渲染地图、监测窗口
    this.fetchInitAlarmDatas()

    // 触发异常预警轮询函数，前端接受最新预警数据后缓存，一段时间后检查缓存，有新数据时触发声音播放
    this.userName = this.$auth && this.$auth.user && this.$auth.user.username

    // 初始化异常数据模拟器，触发模拟异常预警轮询函数，前端接收最新预警数据后先缓存，定时触发声音播放
    this.formInline.enableMock = this.enableMock
    this.mockTrigger = this.initMockTrigger()

    // 初始化用于提醒用户的声音告警频率的轮询函数
    this.formInline.enableVoice = this.enableVoice
    this.alarmTrigger = this.initAlarmTrigger()
  },
  destroyed() {
    clearInterval(this.alarmTrigger)
    clearInterval(this.mockTrigger)
  },
  methods: {
    ...mapMutations({
      cacheAlarmData: 'cacheAlarmData',
      clearNewAlarm: 'clearNewAlarm'
    }),
    ...mapActions({
      fetchInitAlarmDatas: 'fetchInitAlarmDatas'
    }),
    playVoice() {
      let audio = document.getElementById('bell')
      audio.currentTime = 0
      audio.play()
    },
    /**
     * 在前端模拟服务端实时异常警告数据推送
     */
    mockAlarm() {
      // 模拟一条数据
      let data = generateAlarmData()
      // 缓存新数据
      this.cacheAlarmData(data)
    },
    /**
     * 触发前端页面告警
     */
    triggerAlarm() {
      this.$notify({
        title: '异常监测',
        message:
          '系统监测到有 ' +
          this.newAlarms.length +
          ' 条异常信息发生，请注意查验。',
        type: 'warning',
        position: 'bottom-right',
        customClass: 'my-notify'
      })

      this.clearNewAlarm()

      if (this.calcEnableVoice) {
        this.playVoice()
      }
    },
    /**
     * 模拟异常预警轮询函数
     */
    initAlarmTrigger() {
      return setInterval(() => {
        if (this.calcNewAlarms.length > 0) {
          this.triggerAlarm()
        }
      }, this.calcFrequency)
    },
    /**
     * 模拟每间隔0.5~3秒时间，服务端推送一条数据到前端
     */
    getInterval() {
      return Math.max(Math.floor(Math.random() * 4 * 1000), 100)
    },
    /**
     * 声音告警频率的轮询函数
     */
    initMockTrigger() {
      return setInterval(() => {
        if (this.mockWaitTime > this.getInterval() && this.calcEnableMock) {
          this.mockAlarm()
          this.mockWaitTime = 0
        } else {
          this.mockWaitTime += 500
        }
      }, 500)
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/styles/layout.scss';

#switchMock > div,
#switchVoice > div {
  line-height: $lyHeaderHeight;
}

#switchMock > label,
#switchVoice > label {
  margin-left: 10px;
  color: #fff;
}
</style>
